package com.wk.aidldemo.tool.tasktool;

import java.util.HashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class WkHeartBeatTool {
    private ScheduledExecutorService mScheduledExecutorService;
    private HashMap<String, Future> map  ;

    public WkHeartBeatTool() {
        initTool();
    }


    public int getTaskNum(){
        return map==null? 0 : map.size() ;
    }

    private void initTool() {
        mScheduledExecutorService = Executors.newScheduledThreadPool(5);// 线程池大小  5
        map = new HashMap<String, Future>() ;
    }

    public void startTheBeatAction(HeartBeatTask task , int period){
        if(map.containsKey(task.getTaskName())){
            System.out.println("心跳正在进行，无需重复添加");
            return ;
        }
        Future  future = mScheduledExecutorService.scheduleAtFixedRate( task , 0, period, TimeUnit.MILLISECONDS);
        map.put(task.getTaskName() , future) ;
    }

    public void shutDownTheBeatAction(HeartBeatTask task ){
        Future future = map.get(task.getTaskName()) ;
        if(future!=null){
            future.cancel(true) ;
            map.remove(task.getTaskName()) ;
        }else{
            System.out.println("你指定的这个心跳任务已经不存在，无需关闭");
        }
    }

    public void startDelayedAction( HeartBeatTask task , int delayTime){
        mScheduledExecutorService.schedule( task, delayTime ,TimeUnit.MILLISECONDS );
    }

    public void shutDownAll() {
        if (mScheduledExecutorService != null) {
            mScheduledExecutorService.shutdownNow();  // 强制关闭
            mScheduledExecutorService = null;
        }

        map.clear();
        map=null ;
    }

}
